<template>
  <div id="app" class="esign">
    <div class="esign-box" :style="{'position': 'relative','cursor':$attrs.disabled?'not-allowed':'auto'}">
      <vue-esign id="mycanvas" class="esignature" ref="esign" :width="esignWidth" :height="esignHeight" :isCrop="isCrop" :lineWidth="lineWidth" :lineColor="lineColor" :bgColor.sync="bgColor" />
     <div style="width:100%;height: 100%;left:0;top:0;position: absolute;" v-if="isShowCanvas"></div>
    </div>
    <div v-if="isSure">
      <el-button @click="handleClear" size="mini" :disabled="$attrs.disabled" :style="{'cursor':$attrs.disabled?'not-allowed':'auto'}">清空</el-button> 
      <el-button type="primary" size="mini" @click="handleGenerate" :disabled="$attrs.disabled" :style="{'cursor':$attrs.disabled?'not-allowed':'auto'}">确认</el-button>
    </div>
    <div v-if="isReset">
      <el-button @click="handleReset" type="primary" size="mini" :disabled="$attrs.disabled" :style="{'cursor':$attrs.disabled?'not-allowed':'auto'}">重置</el-button> 
    </div>
    <!-- <div class="esigh-result">
      <img v-if="resultImg" :src="resultImg" alt="">
    </div> -->
  </div>
</template>

<script>
import ElementButton from '../bpmnProcessDesigner/package/penal/button/ElementButton.vue'
import { getImgUrl } from "@/api/custom/formDesigner";
import img from '@/assets/images/profile.jpg'
export default {
  components: { ElementButton },
  name: 'App',
  props:{
    value:String,
    esignWidth:{
      type:Number,
      default:800
    },
    esignHeight:{
      type:Number,
      default:300
    }
  },
  data () {
    return {
      lineWidth: 6,
      lineColor: '#000000',
      bgColor: '',
      resultImg: '',
      isCrop: false,
      isShowCanvas:false,
      isSure:true,
      isReset:false
    }
  },
  watch:{
    value:{
      handler(val){
      }
    }
  },
  mounted(){
    // console.log(this.$attrs,'画布');
    this.isShowCanvas = this.$attrs.disabled;
    if(this.$attrs.disabled){
      this.isSure = false
    }
    if(this.value){
      this.doDraw(this.value)
    }
  },
  methods: {
    //绘制图片
    doDraw(imageUrl){
      // 获取canvas
      var canvas = document.getElementById("mycanvas")
      // 由于弹窗，确保已获取到
      var a = setInterval(() =>{
        // 重复获取
        canvas = document.getElementById("mycanvas")
        if(!canvas){
        return false
        } else {
          clearInterval(a)
          // 可以理解为一个画笔，可画路径、矩形、文字、图像
          var context = canvas.getContext('2d')
          var img = new Image()
          img.crossOrigin = ''
          img.src = imageUrl
          let _that = this;
          // 加载图片
          img.onload = function(){
            if(img.complete){
              img.width = _that.esignWidth;
              img.height = _that.esignHeight;
              // 根据图像重新设定了canvas的长宽
              // canvas.setAttribute("width",img.width)
              // canvas.setAttribute("height",img.height)
              // 绘制图片
              context.drawImage(img,0,0,img.width,img.height)
            }
          }
        }
      },1)
    },
    //重置画布
    handleReset () {
      this.isSure = true
      this.isReset = false
      this.isShowCanvas = false
      this.$refs.esign.reset() //清空画布
      this.resultImg = ''
      this.$emit('input', '')
      this.$emit('change', '')
    },
    //清空画布
    handleClear () {
      this.$refs.esign.reset() //清空画布
      this.isShowCanvas = false
      this.resultImg = ''
      this.$emit('input', '')
      this.$emit('change', '')
    },

    //base64转文件
    base64toFile (dataurl, filename) {
      let arr = dataurl.split(',')
      let mime = arr[0].match(/:(.*?);/)[1]
      let suffix = mime.split('/')[1]
      let bstr = atob(arr[1])
      let n = bstr.length
      let u8arr = new Uint8Array(n)
      while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], `${filename}.${suffix}`, {
          type: mime
      })
    },
    //生成图片
    handleGenerate () {
      this.isShowCanvas = true
      this.isSure =false
      this.isReset = true
      this.$refs.esign.generate().then(res => {
      this.resultImg = res
      let file = this.base64toFile(this.resultImg,'filename') //这个file就是base64转成的file文件
      let param = new FormData();
      //添加入参
      param.append("file", file)
      //返回图片获取url
      getImgUrl(
        param
      ).then((res) => {
        if (res.code === 0) {
          this.$emit('input', res.data)
          this.$emit('change', res.data)
        }
      }).catch(e=>console.log(e))
    }).catch(err => { //  没有签名，点击生成图片时调用
        this.$message({
          message: err + ' 未签名！',
          type: 'warning'
        })
        alert(err) // 画布没有签字时会执行这里 'Not Signned'
      })  
    }
  }
}
</script>

<style scoped>
.esign {
  max-width: 1000px;
  margin: auto;
  padding: 10px;
}
.esigh-btns button{
  color: #fff;
  height: 40px;
  width: 100px;
  font-size: 16px;
  margin-right: 10px;
  outline: none;
  border-radius: 4px;
  background: #F60;
  border: 1px solid transparent; 
}
.esigh-btns button:active{ 
  color:#fff; 
  box-shadow: 0px 0px 50px orangered inset; 
}
.esigh-result {
  margin-top: 10px;
}
.esigh-result img {
  display: block;
  max-width: 100%;
  height: auto;
  border: 1px solid #ececee;
}
.esignature {
  margin: 10px 0;
  border: 2px solid #ccc;
}
</style>
